package test.enba.oss.controller;

import com.enba.boot.oss.FileUploadHelper;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/oss")
public class OssController {

  @Autowired private FileUploadHelper fileUploadHelper;

  // 上传文件
  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  public String upload() {
    return fileUploadHelper.uploadFile(new File(""), "bucketName", "objectName");
  }

  // 上传文件
  @RequestMapping(value = "/upload2", method = RequestMethod.POST)
  public String upload2(@RequestParam("file") MultipartFile file) {
    return fileUploadHelper.uploadFile(file, "bucketName", "objectName");
  }

  @Value("${spring.servlet.multipart.location}")
  private String uploadDir;

  @PostMapping("/upload3")
  public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {

    try {
      // 检查空文件
      if (file.isEmpty()) {
        return ResponseEntity.badRequest().body("请选择要上传的文件");
      }

      // 创建存储目录
      Path uploadPath = Paths.get(uploadDir);
      if (!Files.exists(uploadPath)) {
        Files.createDirectories(uploadPath);
      }

      // 生成唯一文件名（可选）
      String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();

      // 保存文件
      Path filePath = uploadPath.resolve(fileName);
      Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

      return ResponseEntity.ok("文件上传成功: " + fileName);

    } catch (IOException e) {
      return ResponseEntity.internalServerError().body("上传失败: " + e.getMessage());
    }
  }
}
